package domo1;

import java.sql.*;
import java.text.MessageFormat;

public class DriverManager {
    public static void main(String[] args) {

        ResultSet resultSet = null;
        Statement statement=null;
        Connection connection=null;
        try {
            //1.加载数据库提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取数据库连接
            connection = java.sql.DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java?characterEncoding" + "=utf8&allowPublicKeyRetrieval=true&useSSL=false",
                    "root", "123456");
            //3.通过Connection获取Statement对象
            statement=connection.createStatement();
            //4.通过Select收集结果集
            resultSet=statement.executeQuery("select id,name,chinese,math,english from exam");
            while (resultSet.next()){
                long id = resultSet.getLong(1);
                String name = resultSet.getString(2);
                int chinese=resultSet.getInt(3);
                int math=resultSet.getInt(4);
                int english=resultSet.getInt(5);
                System.out.println(MessageFormat.format("id={0},name={1},chinese={2},math={3},english={4}",id,name,chinese,math,english));
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        finally {
            //释放结果集
            if (resultSet != null) {
                try{
                    resultSet.close();
                }
                catch (SQLException e){
                    e.printStackTrace();
                }
            }
            //释放statement
            if (statement !=null){
                try {
                    statement.close();
                }
                catch (SQLException e){
                    e.printStackTrace();
                }
            }
            //断开连接
            if (connection !=null){
                try {
                    connection.close();
                }
                catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }

    }
}
